package com.chaofan.controller;

import com.alibaba.fastjson.JSON;
import com.chaofan.entity.User;
import com.chaofan.utils.JsonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//@Controller
@RestController
public class UserController {

    //    @RequestMapping(value = "/t1", produces = "application/json;charser=utf-8")
//    // 不会走视图解析器，直接返回String
//    @ResponseBody
//    public String json() throws JsonProcessingException {
//        User user = new User(1, "超凡", 20);
//
//        ObjectMapper mapper = new ObjectMapper();
//        String str = mapper.writeValueAsString(user);
//
//        return str;
//    }
    @RequestMapping("/t1")
    // 不会走视图解析器，直接返回String
    //@ResponseBody
    public String json() throws JsonProcessingException {
        User user = new User(1, "超凡", 20);

        ObjectMapper mapper = new ObjectMapper();
        String str = mapper.writeValueAsString(user);

        return str;
    }

    @RequestMapping("/t2")
    public String json2() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user1 = new User(1, "超凡1", 20);
        User user2 = new User(2, "超凡2", 20);
        User user3 = new User(3, "超凡3", 20);
        User user4 = new User(4, "超凡4", 20);
        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);


        String str = mapper.writeValueAsString(userList);
        return str;
    }

    /**
     * 时间格式化
     */
    @RequestMapping("/t3")
    public String json3() throws JsonProcessingException {
//        ObjectMapper mapper = new ObjectMapper();
//
//        // 1
//         Date date = new Date();
//        // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//        //2
//        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//
//
//        String str = mapper.writeValueAsString(date);
        Date date = new Date();
        return JsonUtil.toJson(date,"yyyy-MM-dd HH:mm:ss");
    }

    @RequestMapping("/t4")
    public String json4() {
        //String str = JSON.toJSONString(new Date());
        String str = new Gson().toJson(new User(1, "超凡", 20));
        return str;
    }
}
